package hight;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest1 {
    // ReentrantLock可以用来替代Synchroized,在需要同步的代码块加锁，最后一定要释放所，否则其他线程永远
    //进不来
    private Lock lock = new ReentrantLock();

    public void run1() {
        try {
            lock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + "run1");
            Thread.sleep(1000);
            System.out.println("当前线程" + Thread.currentThread().getName() + "退出run1");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
        }

    }
    public void run2() {
        try {
            lock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + "run2");
            Thread.sleep(1000);
            System.out.println("当前线程" + Thread.currentThread().getName() + "退出run2");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        ReentrantLockTest1 reentrantLockTest1 = new ReentrantLockTest1();
        Thread t1 = new Thread(() ->{
            reentrantLockTest1.run1();
            reentrantLockTest1.run2();
        },"t1");
        t1.start();
    }
}
